<?php
class Adminuser_model extends Base_Model
{
    const ADMINUSERTABLE = 'mod_admin_user';

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function getUser($uid)
    {
        return $this->db->get_where(self::ADMINUSERTABLE,array('id'=>$uid))->row_array();
    }

    public function checkUser($email,$token)
    {
        $where = array('email'=>$email,'userToken'=>$token);
        $res = $this->db->get_where(self::ADMINUSERTABLE,$where)->row_array();
        return empty($res) ? false : $res;
    }

    public function checkCaptcha($cap)
    {
        $this->config->load('captcha');
        $exp = $this->config->item('expiration');
        $limit = time() - $exp;
        $this->db->where('created < ',$limit)->delete('common_captcha');

        $res = $this->db->select('count(*) as count')->from('common_captcha')
            ->where('captcha',$cap)
            ->where('ip',$this->input->ip_address())
            ->where('created > ',$limit)->get()->row();
        return $res->count == 0 ? false : true;
    }

    public function login($post = array())
    {
        if (!empty($post['email']) && !empty($post['token'])){
            $res = $this->checkuser($post['email'],md5($post['token']));
            if(!$res) {
                return array("msg"=>"用户名或密码错误","code"=>0);
            } else {
                return $this->checkCaptcha($post['captcha']) ? array("uid"=>$res['id'],"code"=>1)
                    : array("msg"=>"验证码错误","code"=>0);
            }
        }else{
            return array("msg"=>"请输入用户名或密码","code"=>0);
        }
    }

    public function setSession($uid)
    {
        if (!isset($_SESSION)) session_start();
        $_SESSION['uid'] = $uid;
        $_SESSION['utype'] = 'admin';
        $_SESSION['islogin'] = 1;
    }
}